package com.qkl.xiatang.app.web.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qkl.xiatang.app.service.impl.AppURLService;
import com.qkl.xiatang.app.service.impl.AppUserInfoService;
import com.qkl.xiatang.app.utils.*;
import com.qkl.xiatang.app.utils.appenum.AppUserStatus;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component("appInterceptor")
@Slf4j
public  class AppInterceptor implements HandlerInterceptor {

    private ObjectMapper objectMapper = new ObjectMapper();

    @Autowired
    private AppUserInfoService userInfoService;

    @Autowired
    private AppURLService appURLService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
        log.info("uri="+uri);
        AppSessionUtils.removeUser();
        String token = request.getHeader("token");
        String userId = null;
        Result result = null;
        if(!StringUtils.isEmpty(token)) {
            userId = AppTokenUtils.decryptUserId(token);//
            if(StringUtils.isNotEmpty(userId)) {
                AppUserSession session = AppSessionUtils.setUser(userInfoService.queryUser(userId));
                log.info("==========AppUserSession={}",session);
                if(null == session){
                    result = Result.error(ErrorCodeUtils.USER_NOT_EXIST,ErrorCodeUtils.USER_NOT_EXIST_MSG);
                }else if( !token.equals(session.getUser().getToken())){
                    result = Result.error(ErrorCodeUtils.TOKEN_EXPIRE,ErrorCodeUtils.TOKEN_EXPIRE_MSG);
                }else if(!AppUserStatus.isOK(session.getUser().getStatus())){
                    result = Result.error(ErrorCodeUtils.USER_STATUS_EXP,"用户" + AppUserStatus.getName(session.getUser().getStatus()));
                }else if(session.getUser().delete()){
                    result = Result.error(ErrorCodeUtils.USER_STATUS_EXP,"用户已删除");
                }
            }else{
                result = Result.error(ErrorCodeUtils.TOKEN_INVALID,ErrorCodeUtils.TOKEN_INVALID_MSG);
            }
        }else {
            result = Result.error(ErrorCodeUtils.TOKEN_EMPTY, ErrorCodeUtils.TOKEN_EMPTY_MSG);
        }

        if( this.isNotIntercept(uri)){
            return HandlerInterceptor.super.preHandle(request, response, handler);
        }

        if(null != result){
            response.reset();
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().print(objectMapper.writeValueAsString(result));
            response.getWriter().close();
            return false;
        }
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        AppSessionUtils.removeUser();
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }

    private boolean isNotIntercept(String uri){
        return appURLService.notIntercept(uri);
    }

}
